<template>
  <div>
    <!-- 详情 -->
    <div class="layout-container-detail">
      <div class="detail-page-name"><span @click="goRouter('/projectManagement')">项目管理</span> / <span @click="goRouter('/backstagerpzzm/projectDetail/projectDetail')">项目详情</span> / 题目详情</div>
      <div class="detail-page-title">
        <div>
          <span class="detail-title">{{topicInfo.detail.title}}</span>
          <span class="detail-sort">排序值：{{topicInfo.detail.sn}}</span>
        </div>
        <div>
          <!-- 回归题库 只有未生效与闲置中没有 -->
          <el-button v-if="topicInfo.detail.status !== 0 && topicInfo.detail.status !== 5" type="primary" @click="changeTopicStatusFun(5)">回归题库</el-button>
          <el-button v-if="topicInfo.detail.status !== 6" @click="changeTopicStatusFun(6)">作废</el-button>
        </div>
      </div>
      <div>
        <el-row class="el-row-item">
          <el-col :span="8">项目ID：{{topicInfo.detail.project_id}}</el-col>
          <el-col :span="8">题目ID：{{topicInfo.detail.topic_id}}</el-col>
          <el-col :span="8">题目生效时间：{{dateFormat(topicInfo.detail.effective_time)}}</el-col>
          <el-col :span="8">截止时间：{{dateFormat(topicInfo.detail.end_date_time)}}</el-col>
          <el-col :span="8">放弃多次后作废：{{topicInfo.detail.give_up_number}}次</el-col>
          <el-col :span="8">题目状态：
            <!--  0 未生效 1已完成 2 已领取 3指派中 4返修中 5 闲置中 6 已作废 -->
            <span v-if="topicInfo.detail.status === 0">未生效</span>
            <span v-if="topicInfo.detail.status === 1">已完成</span>
            <span v-if="topicInfo.detail.status === 2">已领取</span>
            <span v-if="topicInfo.detail.status === 3">指派中</span>
            <span v-if="topicInfo.detail.status === 4">返修中</span>
            <span v-if="topicInfo.detail.status === 5">闲置中</span>
            <span v-if="topicInfo.detail.status === 6">已作废</span>
          </el-col>
          <el-col :span="8" :offset="0">
                <div class="">
                  题目检索标签：{{topicInfo.detail.labels && topicInfo.detail.labels.join(',')}}
                </div>
              </el-col>
        </el-row>
      </div>
    </div>
    <!-- 题目配置 -->
    <div class="layout-container">
      <div class="layout-container-form" style="flex-direction: column">
        <div class="layout-container-form-title">题目配置</div>
      </div>
      <div class="layout-container-table">
        <div style="text-align: left; padding: 5px">提交配置</div>
        <el-table :data="topicInfo.detail.TopicConfiguration" :loading="!(topicInfo.detail.TopicConfiguration.length>0)" :header-cell-style="getRowClass">
          <el-table-column prop="title" label="表单标题" align="center" >
            <template #default="scope">
              <div v-if="scope.row.editType === 1">
                <el-input v-model="scope.row.title" placeholder="请输入表单标题" />
              </div>
              <div v-else>
                {{scope.row.title}}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="answer_type" label="答题类型" align="center" width="80">
            <template #default="scope">
              <div v-if="scope.row.editType === 1">
                <el-select v-model="scope.row.answer_type" placeholder="请选择答题类型">
                  <el-option label="文本框" :value="0" />
                  <el-option label="上传文件" :value="1" />
                  <el-option label="富文本" :value="2" />
                </el-select>
              </div>
              <div v-else>
                <span v-if="scope.row.answer_type === 1">上传文件</span>
                <span v-if="scope.row.answer_type === 0">文本框</span>
                <span v-if="scope.row.answer_type === 2">富文本</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="required" label="必填选项" align="center" width="80">
            <template #default="scope"> 
              <div v-if="scope.row.editType === 1">
                <el-select v-model="scope.row.required" placeholder="请选择必填选项">
                  <el-option label="必填" :value="0" />
                  <el-option label="选填" :value="1" />
                </el-select>
              </div>
              <div v-else>
                <span v-if="scope.row.required === 0">必填</span>
                <span v-if="scope.row.required === 1">选填</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="tooltip" label="提示文字" align="center">
            <template #default="scope"> 
              <div v-if="scope.row.editType === 1">
                <el-input v-model="scope.row.tooltip" placeholder="请输入提示文字" />
              </div>
              <div v-else>
               {{scope.row.tooltip}}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="is_check" label="上传校验" align="center">
            <template #header>
              上传校验 
              <el-tooltip placement="top">
              <template #content>
                <div style="min-width: 200px; max-width: 400px">
                  开启后限制上传的文件名字需要和题目名字一致，否则不给与上传。
                </div>
              </template>
              <img src="@/assets/images/question-icon.png" alt="" class="question-icon-img">
            </el-tooltip>  
            </template>
            <template #default="scope"> 
              <div v-if="scope.row.editType === 1">
                <el-select v-model="scope.row.is_check" placeholder="请选择上传校验">
                  <el-option label="开启" :value="1" />
                  <el-option label="关闭" :value="0" />
                </el-select>
              </div>
              <div v-else>
                <span v-if="scope.row.is_check === 1">开启</span>
                <span v-if="scope.row.is_check === 0">关闭</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('message.common.handle')"
            align="center"
            fixed="right"
            width="120"
          >
            <template #default="scope">
              <div v-if="!scope.row.editType">
                <el-button type="text" @click="handleOptConfig(scope.row, 'edit', scope.$index)">
                  {{ $t("message.common.edit") }}
                </el-button>
                <span>
                  <span class="split-line">|</span>
                  <el-button type="text" @click="handleOptConfig(scope.row, 'del', scope.$index)">
                    {{ $t("message.common.del") }}
                  </el-button>
                </span>
              </div>
              <div v-else>
                <el-button type="text" @click="handleOptConfig(scope.row, 'save', scope.$index)">
                  保存
                </el-button>
                <span class="split-line">|</span>
                <el-button type="text" @click="handleOptConfig(scope.row, 'cancel', scope.$index)">
                  取消
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="add-question-btn" @click="addConfig">
          <i class="el-icon-plus" /> 添加答题输入内容
        </div>
      </div>
      <div class="layout-container-table">
        <div style="text-align: left; padding: 5px">项目备注:</div>
        <el-table :data="topicInfo.detail.TopicNote" :loading="!(topicInfo.detail.TopicNote.length>0)" :header-cell-style="getRowClass">
          <el-table-column prop="index" label="序号" align="center" width="160">
            <template #default="scope"> 
              <div v-if="scope.row.editType === 1">
                <el-input-number
                 v-model="scope.row.sn"
                 :min="1"
                 :max="999999999999"
                 :precision="0"
                 controls-position="right"
                 placeholder="请输入序号" />
              </div>
              <div v-else>
                {{scope.row.sn}}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="id" label="备注" align="center" >
            <template #default="scope"> 
              <div v-if="scope.row.editType === 1">
                <el-input v-model="scope.row.content" placeholder="请输入备注内容" maxlength="200" show-word-limit/>
              </div>
              <div v-else>
                {{scope.row.content}}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('message.common.handle')"
            align="center"
            fixed="right"
            width="120"
          >
            <template #default="scope">
              <div v-if="!scope.row.editType">
                <el-button type="text" @click="handleOptNote(scope.row, 'edit', scope.$index)">
                  {{ $t("message.common.edit") }}
                </el-button>
                <span class="split-line">|</span>
                <el-button type="text" @click="handleOptNote(scope.row, 'del', scope.$index)">
                  {{ $t("message.common.del") }}
                </el-button>
              </div>
              <div v-else>
                <el-button type="text" @click="handleOptNote(scope.row, 'save', scope.$index)">
                  保存
                </el-button>
                <span class="split-line">|</span>
                <el-button type="text" @click="handleOptNote(scope.row, 'cancel', scope.$index)">
                  取消
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="add-question-btn" @click="addNote">
          <i class="el-icon-plus" /> 添加备注
        </div>
      </div>
    </div>
    <!-- 领取人 -->
    <div class="layout-container">
      <div class="layout-container-form" style="flex-direction: column">
        <div class="layout-container-form-title">领取人</div>
      </div>
      <div class="layout-container-table">
        <el-table :data="topicInfo.user_list" :header-cell-style="getRowClass">
          <el-table-column prop="user_id" label="领取人ID" align="center" />
          <el-table-column prop="real_name" label="领取人姓名" align="center" />
          <el-table-column prop="nick_name" label="领取人昵称" align="center" />
          <el-table-column prop="nick_name" label="身份" align="center" > 
            <template #default="scope">
              <!-- 记录类型 0 放弃题目 1 领取题目 2 提交答案 -->
              <span v-if="scope.row.enum_type === 0">答主老师</span>
              <span v-if="scope.row.enum_type === 1">一审老师</span>
              <span v-if="scope.row.enum_type === 2">二审老师</span>
            </template>
          </el-table-column>
          <el-table-column prop="tp" label="状态" align="center" width="80">
            <template #default="scope">
              <!-- 记录类型 0 放弃题目 1 领取题目 2 提交答案 -->
              <template v-if="scope.row.review_status > 0">
                <span v-if="scope.row.review_status == 1">审核通过</span>
                <span v-if="scope.row.review_status == 2">审核拒绝</span>
              </template>
              <template v-else>
                <span v-if="scope.row.tp === 0">放弃题目</span>
                <span v-if="scope.row.tp === 1">领取题目</span>
                <span v-if="scope.row.tp === 2">提交答案</span>
              </template>
             
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="领取时间" align="center">
            <template #default="scope">
              <span v-if="scope.row.tp === 1 || scope.row.tp === 2">{{dateFormat(scope.row.created_at)}}</span>
              <span v-else>—</span>
             </template>
          </el-table-column>
          <el-table-column prop="tp" label="放弃时间" align="center">
            <template #default="scope"> 
              <span v-if="scope.row.tp === 0">{{dateFormat(scope.row.created_at)}}</span>
              <span v-else>—</span>
            </template>
          </el-table-column>
          <el-table-column prop="give_up_reason" label="放弃原因" align="center" show-overflow-tooltip>
            <template #default="scope">
              <span v-if="scope.row.tp === 0">{{scope.row.give_up_reason}}</span>
              <span v-else>—</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('message.common.handle')"
            align="center"
            fixed="right"
            width="120"
          >
            <template #default="scope">
              <el-button v-if="scope.row.tp === 2" :loading="exportLoading" type="text" @click="handleOpt(scope.row, 'export')">
                {{ $t("message.common.export") }}
              </el-button>
              <span v-else>—</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { dateFormat, prefix } from "@/utils/index.ts";
import { defineComponent, ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { createdTopicConfig, editTopicConfig, delTopicConfig, createTopicNote, editTopicNote, delTopicNote, getTopicDetail, changeTopicStatus, exportExcel, topicUserRecordList} from "@/api/service/project.ts";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
const router = useRouter();
const store = useStore();
const adminInfo = reactive(store.state.user.adminInfo);
// console.log(store.state.user.topicInfo)
let topicInfoData = JSON.parse(JSON.stringify(store.state.user.topicInfo)) 

// 题目详情数据
const topicInfo = reactive({
  // ...topicInfoData
  detail: {...topicInfoData},
  user_list: []
})
topicInfo.detail.TopicConfiguration = [];
topicInfo.detail.TopicNote = [];

const getRowClass = ({ rowIndex, columnIndex }) => {
  if (rowIndex == 0) {
    return "background:#f8f8f9;color:#313131;";
  }
};

// 面包屑路由跳转
const goRouter = (path: String) => {
  router.push({
    path: path
  })
}

// 获取题目详情
const getTopicDetailFun = () => {
  let data = {
    id: topicInfo.detail.Id
  }
  getTopicDetail(data).then((res: any) => {
    if (res.code === 200) {
      let data = res.data
      topicInfo.detail.TopicConfiguration = data.detail.TopicConfiguration
      topicInfo.detail.TopicNote = data.detail.TopicNote
      topicInfo.detail.status = data.detail.status
      // topicInfo.user_list = data.user_list
    }
  })
}
const topicUserRecordListFunc =() =>{
   let data = {
    topic_id: topicInfo.detail.topic_id + '',
    // project_id: topicInfo.detail.project_id
  }
  topicUserRecordList(data).then((res: any) => {
    if (res.code === 200) {
      debugger
      let data = res.data
      topicInfo.user_list = data.list
    }
  })
}
topicUserRecordListFunc()
getTopicDetailFun();


// 回归题库,返修,作废
const changeTopicStatusFun = (status: Number) => {
  ElMessageBox.confirm(`是否确认当前操作?`, "", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "success",
  })
  .then(() => {
    console.log(topicInfo)
    let data = {
      id: topicInfo.detail.Id,
      status: status
    }
    changeTopicStatus(data).then((res: any) => {
      if (res.code === 200) {
        let msg = ''
        if(status === 5){
          msg = '回归题库成功！'
        }
        if(status === 6){
          msg = '作废成功！'
        }
        ElMessage.success(msg);
        getTopicDetailFun();
      }
    })
  })
  .catch(() => {});
}

// 添加答题输入内容事件
const addConfig = () => {
  let config = {
    answer_type: '', // integer 题目作答类型 0 文本框 1 上传文件
    is_check: '', // integer 上传文件是否校验名称 0不校验 1 校验
    required: '', // integer 是否必填 0 选填 1必填
    system_topic_id: topicInfo.detail.Id, // integer 关联的题目Id
    title: '', // string 表单标题
    tooltip: '', // string 提示文本
    topic_id: topicInfo.detail.topic_id, // string 用户自定义的题目Id
    editType: 1 // 1:编辑 0:非编辑状态
  };
  topicInfo.detail.TopicConfiguration.push(config);
}

// 题目配置数据操作
const handleOptConfig = (row: any, type: String, i: Number) => {
  ElMessageBox.confirm(`是否确认当前操作?`, "", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "success",
  })
    .then(() => {
      if (type === "save") {
        if (!row.title) {
          ElMessage.error("请输入表单标题");
          return;
        }
        if (row.answer_type === "") {
          ElMessage.error("请选择答题类型");
          return;
        }
        if (row.required === "") {
          ElMessage.error("请选择必填项");
          return;
        }
        if (!row.tooltip) {
          ElMessage.error("请输入提示文字");
          return;
        }
        if (row.is_check === "") {
          ElMessage.error("请选择上传校验");
          return;
        }
        if (!row.Id) {
          createdTopicConfigFun(row, i)
        } else {
          editTopicConfigFun(row, i)
        }
      }
      if (type === "cancel") {
        if (topicInfo.detail.TopicConfiguration[i].Id) {
          topicInfo.detail.TopicConfiguration[i].editType = 0;
        } else {
          topicInfo.detail.TopicConfiguration.splice(i, 1)
        }
      }
      if (type === "edit") {
        topicInfo.detail.TopicConfiguration[i].editType = 1;
      }
      if (type === "del") {
        deleteConfigFun(row.Id, i)
      }
    })
    .catch(() => {});
};
// 题目配置数据操作-保存
const createdTopicConfigFun = (row: any, i: Number) => {
  let data = {
    //  answer_type: Number(row.answer_type), // integer 题目作答类型 0 文本框 1 上传文件
    //   is_check: Number(row.is_check), // integer 上传文件是否校验名称 0不校验 1 校验
    //   required: Number(row.required), // integer 是否必填 0 选填 1必填
    //   system_topic_id: row.system_topic_id, // integer 关联的题目Id
    //   title: row.title, // string 表单标题
    //   tooltip: row.tooltip, // string 提示文本
    //   topic_id: row.topic_id, // string 用户自定义的题目Id
    ...row
  }
  createdTopicConfig(data).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success("保存成功！")
      topicInfo.detail.TopicConfiguration[i].editType = 0;
      // store.commit('user/topicInfoChange', topicInfo)
      getTopicDetailFun()
    }
  })
}
// 题目配置数据操作-保存的修改操作
const editTopicConfigFun = (row: any, i: Number) => {
  let data = {
    ...row
  }
  editTopicConfig(data).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success("保存成功！")
      topicInfo.detail.TopicConfiguration[i].editType = 0;
      // store.commit('user/topicInfoChange', topicInfo)
      getTopicDetailFun()
    }
  })
}
// 删除题目配置函数
const deleteConfigFun = (id: any, i: Number) => {
  let data = {
    id,
  };
  delTopicConfig(data)
  	.then((res: any) => {
  		if (res.code == 200) {
  			ElMessage.success("删除成功！");
        topicInfo.detail.TopicConfiguration.splice(i, 1)
        // store.commit('user/topicInfoChange', topicInfo)
        getTopicDetailFun()
  		} else {
  			ElMessage.error("删除失败！");
  		}
  	})
  	.catch(() => false);
};


// 添加配置
const addNote = () => {
  let config = {
    content: '', // string 题目备注文本
    sn: '', // integer 序号
    system_topic_id: topicInfo.detail.Id, // integer 题目数据库Id
    topic_id: topicInfo.detail.topic_id, // string 题目自定义 Id
    editType: 1 // 1:编辑 0:非编辑状态
  };
  topicInfo.detail.TopicNote.push(config);
}

// 题目备注数据操作
const handleOptNote = (row: any, type: String, i: Number) => {
  ElMessageBox.confirm(`是否确认当前操作?`, "", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "success",
  })
    .then(() => {
      if (type === "save") {
        if (row.sn === "") {
          ElMessage.error("请输入序号");
          return;
        }
        if (row.content === "") {
          ElMessage.error("请输入备注内容");
          return;
        }
        if (!row.Id) {
          createTopicNoteFun(row, i)
        } else {
          editTopicNoteFun(row, i)
        }
      }
      if (type === "cancel") {
        if (topicInfo.detail.TopicNote[i].Id) {
          topicInfo.detail.TopicNote[i].editType = 0;
        } else {
          topicInfo.detail.TopicNote.splice(i, 1);
        }
      }
      if (type === "edit") {
        topicInfo.detail.TopicNote[i].editType = 1;
      }
      if (type === "del") {
        deleteNoteFun(row.Id, i)
      }
    })
    .catch(() => {});
};
// 题目备注数据操作-保存
const createTopicNoteFun = (row: any, i: Number) => {
  let data = {
    //  answer_type: Number(row.answer_type), // integer 题目作答类型 0 文本框 1 上传文件
    //   is_check: Number(row.is_check), // integer 上传文件是否校验名称 0不校验 1 校验
    //   required: Number(row.required), // integer 是否必填 0 选填 1必填
    //   system_topic_id: row.system_topic_id, // integer 关联的题目Id
    //   title: row.title, // string 表单标题
    //   tooltip: row.tooltip, // string 提示文本
    //   topic_id: row.topic_id, // string 用户自定义的题目Id
    ...row
  }
  createTopicNote(data).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success("保存成功！")
      topicInfo.detail.TopicNote[i].editType = 0;
      // store.commit('user/topicInfoChange', topicInfo)
      getTopicDetailFun()
    }
  })
}
// 题目备注数据操作-保存的修改操作
const editTopicNoteFun = (row: any, i: Number) => {
  let data = {
    ...row
  }
  editTopicNote(data).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success("保存成功！")
      topicInfo.detail.TopicNote[i].editType = 0;
      // store.commit('user/topicInfoChange', topicInfo)
      getTopicDetailFun()
    }
  })
}
// 删除题目备注函数
const deleteNoteFun = (id: any, i: Number) => {
  let data = {
    id,
  };
  delTopicNote(data)
  	.then((res: any) => {
  		if (res.code == 200) {
  			ElMessage.success("删除成功！");
        topicInfo.detail.TopicNote.splice(i, 1)
        // store.commit('user/topicInfoChange', topicInfo)
        getTopicDetailFun()
  		} else {
  			ElMessage.error("删除失败！");
  		}
  	})
  	.catch(() => false);
};

// 导出通用函数
const exportExcelPost = (topic_ids: any, project_ids: any) => {
  exportLoading.value = true;
  let data = {
    topic_ids: topic_ids, // array[interger]
    project_ids: project_ids, // array[string]
  }
  exportExcel(data).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success('导出成功');
      window.open(res.data);
    }
  }).finally(() => {
    exportLoading.value = false;
  })
}
// 操作导出
const exportLoading = ref(false);
const handleOpt = (row: any, type: String) => {
  ElMessageBox.confirm(`是否确认当前操作?`, "", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "success",
  })
    .then(() => {
      // 导出
      if (type === "export") {
        let topic_ids = [row.system_topic_id]; // array[interger]
        let project_ids = [row.project_id]; // array[string]
        exportExcelPost(topic_ids, project_ids);
      }
    })
    .catch(() => {});
};


</script>

<style lang="scss" scoped>
.layout-container {
  height: auto;
}
.layout-container-table{
  flex:none;
}
.layout-container-form {
  position: relative;
  padding: 0;
  .layout-container-form-title {
    border-bottom: 1px solid #eeeeee;
    padding: 20px;
    font-size: 18px;
    font-size: bold;
    text-align: left;
    margin-bottom: 10px;
  }
}
.layout-container-detail {
  text-align: left;
  background: #ffffff;
  padding: 20px;
  box-sizing: border-box;
  .detail-page-name {
    color: #9a9b9f;
    margin-bottom: 20px;
    span{
      cursor: pointer;
    }
  }
  .detail-page-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    .detail-title {
      font-size: 20px;
      font-weight: bold;
      margin-right: 10px;
    }
    .detail-sort {
      font-size: 12px;
    }
  }
  .el-row-item {
    :deep(.el-col) {
      margin-bottom: 25px;
      display: flex;
      align-items: center;
      font-size: 14px;
      color: #000000;
    }
  }
}
.layout-container-form-search {
  width: 100%;
  display: inline-block !important;
  justify-content: flex-start !important;
  padding: 0 20px;
  .search-btn {
    margin-right: 10px;
  }
}
.layout-container-opt {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 5px 20px;
}
.split-line {
  margin: 0 8px;
  color: #ccc;
}
.image-slot {
  width: 50px;
  height: 50px;
  background: #fafafa;
  color: #ccc;
  font-size: 12px;
  cursor: pointer;
}
.popperClass {
  background: #000000;
}
.add-question-btn {
  width: 100%;
  border: 1px dashed #ccc;
  text-align: center;
  padding: 10px 0;
  margin-top: 10px;
  color: #9a9b9f;
  font-size: 14px;
  cursor: pointer;
}

.question-icon-img{
  position: relative;
  top: 3px;
  width: 15px;
}
</style>
